/*
 * Copyright (c) 2015 elion All Rights Reserved.
 */
package com.guoyu.project.common.velocity;

import java.io.IOException;
import java.io.Writer;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;

/**
 * 覆盖#block指令显示的内容
 * 
 * @author: xblibo Date: 2015/5/18 Time: 13:44
 */
public class OverrideDirective extends Directive {

    /**
     * 定义重写块的标签名
     */
    private final static String OVERRIDE_TAG = "override";

    @Override
    public String getName() {
        return OVERRIDE_TAG;
    }

    @Override
    public int getType() {
        return BLOCK;
    }

    @Override
    public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException,
            ResourceNotFoundException, ParseErrorException, MethodInvocationException {

        String name = VelocitySupports.getRequiredArgument(context, node, 0, getName());
        OverrideNodeWrapper override = (OverrideNodeWrapper) context
                .get(VelocitySupports.getOverrideVariableName(name));
        if (override == null) {
            Node body = node.jjtGetChild(1);
            context.put(VelocitySupports.getOverrideVariableName(name), new OverrideNodeWrapper(body));
        } else {
            OverrideNodeWrapper current = new OverrideNodeWrapper(node.jjtGetChild(1));
            VelocitySupports.setParentForTop(current, override);
        }
        return true;
    }
}
